package models

import (
	"context"
	"fmt"
	"github.com/spf13/viper"
	"log"
	"time"

	"github.com/go-redis/redis/v8"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
)

func initConfig() {
	viper.SetConfigName("app")
	viper.AddConfigPath("config")
	err := viper.ReadInConfig()
	if err != nil {
		fmt.Println(err)
	}
	fmt.Println(" mongodb.url=", viper.GetString("mongodb.url"))
	fmt.Println(" redis.addr=", viper.GetString("redis.addr"))
	fmt.Println(" redis.password=", viper.GetString("redis.password"))
	fmt.Println("config  app inited 。。。。")
}

var MongoDB = InitMongo()
var RDB = InitRedis()

func InitMongo() *mongo.Database {
	initConfig()
	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
	defer cancel()
	mongodburl := viper.GetString("mongodb.url")
	client, err := mongo.Connect(ctx, options.Client().ApplyURI(mongodburl))

	//client, err := mongo.Connect(ctx, options.Client().ApplyURI("mongodb://192.168.0.129:27017"))
	if err != nil {
		log.Println("Connection MongoDB Error: ", err)
		return nil
	}
	return client.Database("im")
}

func InitRedis() *redis.Client {
	return redis.NewClient(&redis.Options{
		Addr:     viper.GetString("redis.addr"),
		Password: viper.GetString("redis.password"), // no password set
		DB:       0,                                 // use default DB
	})
}
